<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.9.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2"><link rel="stylesheet" href="/css/main.css?v=7.1.1"><link rel="apple-touch-icon" sizes="180x180" href="/images/my-apple-touch-icon-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="32x32" href="/images/my-32x32-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="16x16" href="/images/my-16x16-next.png?v=7.1.1"><link rel="mask-icon" href="/images/my-logo.svg?v=7.1.1" color="#222"><script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script><meta name="description" content="本文总结了 C/C++ 中动态内存分配的方法，malloc \ free \ calloc 函数的用法，new delete 的用法及其与 C 语言中函数的区别，operator new \ placement new \ operator delete 的原理与使用"><meta name="keywords" content="C,C++,动态内存管理,malloc,free,new,delete"><meta property="og:type" content="article"><meta property="og:title" content="C&#x2F;C++动态内存管理"><meta property="og:url" content="https://renshengjihe.cn/190804-CCppDynamicMemory.html"><meta property="og:site_name" content="dhd的博客"><meta property="og:description" content="本文总结了 C/C++ 中动态内存分配的方法，malloc \ free \ calloc 函数的用法，new delete 的用法及其与 C 语言中函数的区别，operator new \ placement new \ operator delete 的原理与使用"><meta property="og:locale" content="zh-CN"><meta property="og:updated_time" content="2019-11-18T07:46:11.997Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="C&#x2F;C++动态内存管理"><meta name="twitter:description" content="本文总结了 C/C++ 中动态内存分配的方法，malloc \ free \ calloc 函数的用法，new delete 的用法及其与 C 语言中函数的区别，operator new \ placement new \ operator delete 的原理与使用"><link rel="canonical" href="https://renshengjihe.cn/190804-CCppDynamicMemory"><script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script><title>C/C++动态内存管理 | dhd的博客</title><noscript><style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">dhd的博客</span><span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">对酒当歌，人生几何</h1></div><div class="site-nav-toggle"> <button aria-label="切换导航栏"><span class="btn-bar"></span><span class="btn-bar"></span><span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li></ul></nav></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://renshengjihe.cn/190804-CCppDynamicMemory.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="dhd"><meta itemprop="description" content="个人博客,分享一些C/C++ Linux 相关的学习笔记"><meta itemprop="image" content="/images/avatar.gif"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="dhd的博客"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">C/C++动态内存管理</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建时间：2019-08-04 09:57:23" itemprop="dateCreated datePublished" datetime="2019-08-04T09:57:23+08:00">2019-08-04</time> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i></span> <span class="post-meta-item-text">更新于</span> <time title="修改时间：2019-11-18 15:46:11" itemprop="dateModified" datetime="2019-11-18T15:46:11+08:00">2019-11-18</time></span> <span class="post-category"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/C-C/" itemprop="url" rel="index"><span itemprop="name">C/C++</span></a></span></span> <span class="post-comments-count"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i></span> <span class="post-meta-item-text">评论数：</span><a href="/190804-CCppDynamicMemory.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/190804-CCppDynamicMemory.html" itemprop="commentCount"></span></a></span> <span id="/190804-CCppDynamicMemory.html" class="leancloud_visitors" data-flag-title="C/C++动态内存管理"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span class="leancloud-visitors-count"></span></span><div class="post-description">本文总结了 C/C++ 中动态内存分配的方法，malloc \ free \ calloc 函数的用法，new delete 的用法及其与 C 语言中函数的区别，operator new \ placement new \ operator delete 的原理与使用</div></div></header><div class="post-body" itemprop="articleBody"><p>在 C 和 C++ 中，对于动态内存的管理是一个永恒的话题，C语言采用 x(x)alloc 和 free 来开辟和释放动态内存空间，不同的是，C++ 引入了 new 和 delete 操作符作为新的方式。这二者有什么区别呢？new \ delete 又有哪些高级用法，这些都将在下文一一列出。</p><h2 id="malloc-free-calloc-realloc"><a href="#malloc-free-calloc-realloc" class="headerlink" title="malloc \ free \ calloc \ realloc"></a>malloc \ free \ calloc \ realloc</h2><h3 id="malloc"><a href="#malloc" class="headerlink" title="malloc"></a>malloc</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span>* <span class="title">malloc</span><span class="params">(<span class="keyword">size_t</span> size)</span></span>;</span><br></pre></td></tr></table></figure><p>开辟一段 size 字节大小的内存空间，并将空间的首地址返回，如果 size 为 0 ,则返回空指针。</p><h3 id="free"><a href="#free" class="headerlink" title="free"></a>free</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">free</span><span class="params">(<span class="keyword">void</span>* p)</span></span>;</span><br></pre></td></tr></table></figure><p>释放一段指针指向的内存空间。</p><h3 id="calloc"><a href="#calloc" class="headerlink" title="calloc"></a>calloc</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span>* <span class="title">calloc</span><span class="params">(<span class="keyword">size_t</span> nmemb, <span class="keyword">size_t</span> size)</span></span>;</span><br></pre></td></tr></table></figure><p>开辟一段连续的内存空间，它的大小为 nmemb * size 字节，并为每一块内存地址赋 0，它实际上依然调用了 malloc 只是在 malloc 的基础上进行了额外的操作。</p><h3 id="realloc"><a href="#realloc" class="headerlink" title="realloc"></a>realloc</h3><p>函数原型<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span>* <span class="title">realloc</span><span class="params">(<span class="keyword">void</span>* ptr, <span class="keyword">size_t</span> size)</span></span>;</span><br></pre></td></tr></table></figure><p></p><p>重新开辟一段内存空间，将传入的指针 ptr 所指地址的空间调整至 size 大小。如果 size 比原来的空间大，会在另一个地址处开辟一段新的空间，而 ptr 所指的空间被释放；否则，返回的地址仍然是原先的地址，只是合法空间的大小经过了调整。不过即使 realloc 可能返回与 ptr 相同的首地址，但大多数情况下仍然要以下面的方式来使用 realloc 从而避免多次释放的问题。<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> *p = (<span class="keyword">int</span>*)<span class="built_in">malloc</span>(<span class="number">5</span>*<span class="keyword">sizeof</span>(<span class="keyword">int</span>));</span><br><span class="line">    p = <span class="built_in">realloc</span>(p, <span class="number">10</span>*<span class="keyword">sizeof</span>(<span class="keyword">int</span>));     <span class="comment">// 传入参数 p 的地址在 realloc 中已经被释放</span></span><br><span class="line">    <span class="built_in">free</span>(p);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><h2 id="new-delete"><a href="#new-delete" class="headerlink" title="new \ delete"></a>new \ delete</h2><p>new 和 delete 是 C++ 中新增的动态内存管理的两个运算符，下面是 new 和 delete 的用例。<br></p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> *p1 = <span class="keyword">new</span> <span class="keyword">int</span>(<span class="number">0</span>);   <span class="comment">// 一个整形空间，初始化为 0</span></span><br><span class="line">    <span class="keyword">int</span> *p2 = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">5</span>];   <span class="comment">// 五个整形空间</span></span><br><span class="line">    <span class="keyword">delete</span> p1;              <span class="comment">// 释放单个空间</span></span><br><span class="line">    <span class="keyword">delete</span>[] p2;            <span class="comment">// 释放连续空间</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><h2 id="两种方式的区别"><a href="#两种方式的区别" class="headerlink" title="两种方式的区别"></a>两种方式的区别</h2><p>下表总结了两种方式之间的区别</p><table><thead><tr><th style="text-align:right">特征</th><th style="text-align:left">new \ delete</th><th style="text-align:left">malloc \ free</th><th style="text-align:left">解释</th></tr></thead><tbody><tr><td style="text-align:right">分配内存的位置</td><td style="text-align:left">自由存储区</td><td style="text-align:left">堆区</td><td style="text-align:left">new 和 delete 可以重载，分配到那个存储区取决于具体实现。</td></tr><tr><td style="text-align:right">返回指针的类型</td><td style="text-align:left">完整的类型</td><td style="text-align:left">void*</td><td style="text-align:left">new 开辟出的内存空间不用像 malloc 那样做类型转换，使用起来更方便</td></tr><tr><td style="text-align:right">分配失败的处理</td><td style="text-align:left">抛出异常</td><td style="text-align:left">返回NULL</td><td style="text-align:left">抛出异常处理起来更加灵活</td></tr><tr><td style="text-align:right">分配内存的大小</td><td style="text-align:left">由编译器根据类型计算</td><td style="text-align:left">必须显示指定字节数</td><td style="text-align:left"></td></tr><tr><td style="text-align:right">处理连续空间</td><td style="text-align:left">new[]</td><td style="text-align:left">必须用户计算数组大小后进行分配</td><td style="text-align:left"></td></tr><tr><td style="text-align:right">已分配内存的扩充</td><td style="text-align:left">无法直观地处理</td><td style="text-align:left">使用 realloc 完成</td><td style="text-align:left"></td></tr><tr><td style="text-align:right">是否相互调用</td><td style="text-align:left">可以，取决于重载的实现</td><td style="text-align:left">不可调用 new 和 delete</td><td style="text-align:left"></td></tr><tr><td style="text-align:right">分配内存时内存不足</td><td style="text-align:left">无法通过用户代码处理</td><td style="text-align:left">能够使用 realloc 函数或重新制定分配器</td><td style="text-align:left"></td></tr><tr><td style="text-align:right">函数重载</td><td style="text-align:left">允许</td><td style="text-align:left">不允许</td><td style="text-align:left"></td></tr><tr><td style="text-align:right">构造与析构</td><td style="text-align:left">调用</td><td style="text-align:left">不调用</td><td style="text-align:left">new 和 delete 为对象开辟/释放空间时会调用对应的构造、析构函数，这在面向对象的程序中极为重要</td></tr></tbody></table><h2 id="operator-new-placement-new-operator-delete"><a href="#operator-new-placement-new-operator-delete" class="headerlink" title="operator new \ placement new \ operator delete"></a>operator new \ placement new \ operator delete</h2><p>上面我们说的 <code>new</code> 运算符是 <code>new operator</code> 而不是 <code>operator new</code></p><p>这两者的区别在于 <code>new operator</code> 的行为是不可以被改变的，它稳定地完成两个任务：</p><ol><li>分配内存（调用的是 <code>operator new</code>）</li><li>调用构造函数初始化</li></ol><p>同样 <code>delete operator</code> 也是一样的道理</p><p>所谓的重载 <code>new</code> 和 <code>delete</code> 其实重载的是 <code>operator new</code> 和 <code>operator delete</code> 而不是 <code>new operator</code> 和 <code>delete operator</code></p><h3 id="operator-new"><a href="#operator-new" class="headerlink" title="operator new"></a>operator new</h3><p>下面是几个 <code>operator new</code> 的原型（定义在 <code>new</code> 文件中）<br></p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 普通 operator new 版本，如果内存开辟失败，会抛出异常</span></span><br><span class="line"><span class="function"><span class="keyword">void</span>* <span class="keyword">operator</span> <span class="title">new</span> <span class="params">(<span class="built_in">std</span>::<span class="keyword">size_t</span> size)</span> <span class="title">throw</span> <span class="params">(<span class="built_in">std</span>::bad_alloc)</span></span>; </span><br><span class="line"><span class="keyword">void</span>* <span class="keyword">operator</span> <span class="keyword">new</span>[] (<span class="built_in">std</span>::<span class="keyword">size_t</span> size) <span class="keyword">throw</span> (<span class="built_in">std</span>::bad_alloc); </span><br><span class="line"><span class="comment">// 第二个参数没有实际的传输数据，它的作用在于标识这个函数不会抛出异常</span></span><br><span class="line"><span class="function"><span class="keyword">void</span>* <span class="keyword">operator</span> <span class="title">new</span> <span class="params">(<span class="built_in">std</span>::<span class="keyword">size_t</span> size, <span class="keyword">const</span> <span class="built_in">std</span>::<span class="keyword">nothrow_t</span>&amp; nothrow_constant)</span> <span class="title">throw</span><span class="params">()</span></span>; </span><br><span class="line"><span class="keyword">void</span>* <span class="keyword">operator</span> <span class="keyword">new</span>[] (<span class="built_in">std</span>::<span class="keyword">size_t</span> size, <span class="keyword">const</span> <span class="built_in">std</span>::<span class="keyword">nothrow_t</span>&amp; nothrow_constant) <span class="keyword">throw</span>();</span><br></pre></td></tr></table></figure><p></p><p>如果要使用第二个版本的 <code>operator new</code>，需要在使用 <code>new operator</code>时按下面的方式使用。<br></p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> *p = <span class="keyword">new</span>(<span class="built_in">std</span>::nothrow) <span class="keyword">int</span>(<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">delete</span> p;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>同样，我们可以自己重写或者重载 <code>operator new</code>，如下：<br></p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span>* <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="keyword">size_t</span> size, <span class="keyword">const</span> <span class="keyword">char</span>* str)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"operator new "</span>  &lt;&lt; str &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">malloc</span>(size);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>* p = <span class="keyword">new</span>(<span class="string">"hello"</span>) <span class="keyword">int</span>(<span class="number">3</span>);</span><br><span class="line">    <span class="keyword">delete</span> []p;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>程序执行结果为：</p><blockquote><p>operator new hello ..</p></blockquote><h3 id="placement-new"><a href="#placement-new" class="headerlink" title="placement new"></a>placement new</h3><p>在 <code>new</code> 文件中，还定义了一个类型的 <code>operaotr new</code>，原型如下：<br></p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Default placement versions of operator new.</span></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="keyword">void</span>* <span class="keyword">operator</span> <span class="title">new</span><span class="params">(<span class="built_in">std</span>::<span class="keyword">size_t</span>, <span class="keyword">void</span>* __p)</span> _GLIBCXX_USE_NOEXCEPT</span></span><br><span class="line"><span class="function"></span>&#123; <span class="keyword">return</span> __p; &#125;</span><br><span class="line"><span class="keyword">inline</span> <span class="keyword">void</span>* <span class="keyword">operator</span> <span class="keyword">new</span>[](<span class="built_in">std</span>::<span class="keyword">size_t</span>, <span class="keyword">void</span>* __p) _GLIBCXX_USE_NOEXCEPT</span><br><span class="line">&#123; <span class="keyword">return</span> __p; &#125;</span><br></pre></td></tr></table></figure><p></p><p>这便是 <code>placement new</code>，它的作用在于在一个已经分配的内存空间上构造一个对象，其语法如下：<br></p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">char</span> a[<span class="number">4</span>] = &#123;<span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>&#125;;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; hex &lt;&lt; &amp;a &lt;&lt; dec &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="keyword">int</span> *p = <span class="keyword">new</span>(&amp;a) <span class="keyword">int</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; hex &lt;&lt; p &lt;&lt; dec &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; *p &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>程序执行结果为：</p><blockquote><p>0x7ffd738daa24<br>0x7ffd738daa24<br>257</p></blockquote><h3 id="operator-delete"><a href="#operator-delete" class="headerlink" title="operator delete"></a>operator delete</h3><p>同样，<code>operator delete</code> 也可以像 <code>operator new</code> 那样进行重载操作，如下：<br></p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="keyword">operator</span> <span class="title">delete</span><span class="params">(<span class="keyword">void</span>* ptr)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">"operator delete"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">free</span>(ptr);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> *p = <span class="keyword">new</span> <span class="keyword">int</span>;</span><br><span class="line">    <span class="keyword">delete</span>(p);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>执行结果为：</p><blockquote><p>operator delete</p></blockquote></div><footer class="post-footer"><div class="post-tags"> <a href="/tags/C-C/" rel="tag"># C/C++</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/190801-DesignPatternDecorator.html" rel="next" title="设计模式-装饰模式(Decorator)"><i class="fa fa-chevron-left"></i> 设计模式-装饰模式(Decorator)</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"> <a href="/190812-DesignPatternBridge.html" rel="prev" title="设计模式-桥模式(Bridge)">设计模式-桥模式(Bridge)<i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span><span class="sidebar-toggle-line sidebar-toggle-line-middle"></span><span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap"> 站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><p class="site-author-name" itemprop="name">dhd</p><div class="site-description motion-element" itemprop="description">个人博客,分享一些C/C++ Linux 相关的学习笔记</div></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">16</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/"><span class="site-state-item-count">7</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/"><span class="site-state-item-count">8</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="mailto:donghaodong555@foxmail.com" title="E-Mail &rarr; mailto:donghaodong555@foxmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a></span></div></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#malloc-free-calloc-realloc"><span class="nav-number">1.</span> <span class="nav-text">malloc \ free \ calloc \ realloc</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#malloc"><span class="nav-number">1.1.</span> <span class="nav-text">malloc</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#free"><span class="nav-number">1.2.</span> <span class="nav-text">free</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#calloc"><span class="nav-number">1.3.</span> <span class="nav-text">calloc</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#realloc"><span class="nav-number">1.4.</span> <span class="nav-text">realloc</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#new-delete"><span class="nav-number">2.</span> <span class="nav-text">new \ delete</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#两种方式的区别"><span class="nav-number">3.</span> <span class="nav-text">两种方式的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#operator-new-placement-new-operator-delete"><span class="nav-number">4.</span> <span class="nav-text">operator new \ placement new \ operator delete</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#operator-new"><span class="nav-number">4.1.</span> <span class="nav-text">operator new</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#placement-new"><span class="nav-number">4.2.</span> <span class="nav-text">placement new</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#operator-delete"><span class="nav-number">4.3.</span> <span class="nav-text">operator delete</span></a></li></ol></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2019</span><span class="with-love" id="animate"><i class="fa fa-user"></i></span> <span class="author" itemprop="copyrightHolder">dhd</span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i></div></div><script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script><script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/lib/canvas-nest/canvas-nest.min.js"></script><script src="/lib/jquery/index.js?v=2.1.3"></script><script src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script src="/js/utils.js?v=7.1.1"></script><script src="/js/motion.js?v=7.1.1"></script><script src="/js/affix.js?v=7.1.1"></script><script src="/js/schemes/pisces.js?v=7.1.1"></script><script src="/js/scrollspy.js?v=7.1.1"></script><script src="/js/post-details.js?v=7.1.1"></script><script src="/js/next-boot.js?v=7.1.1"></script><script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script><script src="//unpkg.com/valine/dist/Valine.min.js"></script><script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'f6cPnWydCEaioX6iq6AoSBPz-gzGzoHsz',
    appKey: 'TRF9THIRqNFdQRvrCURnmfBG',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: '' || 'zh-cn'
  });
</script><script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz',
                'X-LC-Key': 'N3zDUUUGyqewKV2RLoozARF2',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script><script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script><script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script></body></html>